/***************************************************************************
 *   Copyright (C) 2014 by Docteur Pierre-Marie Desombre.   *
 *   pm.desombre@medsyn.fr  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "ficheannuelle.h"
#include "constants.h"
#include "showfiche.h"

#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

using namespace Constants;
using namespace ToolsSpace;

FicheAnnuelle::FicheAnnuelle(QWidget * parent)
{
    Q_UNUSED(parent);
    setupUi(this);
    label->hide();
    m_tools = new Tools(this);
    m_document = new QTextDocument(this);
    m_dbdrtux = QSqlDatabase::database(DRTUXTEST_DB);
    int year = QDate::currentDate().year();
    beginDateEdit->setDisplayFormat("yyyy-MM-dd");
    beginDateEdit->setDate(QDate(year,01,01));
    endDateEdit->setDisplayFormat("yyyy-MM-dd");
    endDateEdit->setDate(QDate::currentDate());    
    m_hashTypeAndCheckBox.insert(TERRAIN,terrainBox);
    m_hashTypeAndCheckBox.insert(DOCUMENTS,documentsBox);
    m_hashTypeAndCheckBox.insert(ORDONNANCE_AJUSTABLE,prescriptionsBox);
    m_hashTypeAndCheckBox.insert(OBSERVATION,observationsBox);
    connect(beginButton,SIGNAL(pressed()),this,SLOT(pushDateOnBeginning()));
    connect(quitButton,SIGNAL(pressed()),this,SLOT(close()));
    connect(okButton,SIGNAL(pressed()),this,SLOT(findDatas()));
    connect(terrainBox,SIGNAL(clicked(bool)),this,SLOT(showHeads(bool)));
    connect(documentsBox,SIGNAL(clicked(bool)),this,SLOT(showHeads(bool)));
    connect(observationsBox,SIGNAL(clicked(bool)),this,SLOT(showHeads(bool)));
    connect(prescriptionsBox,SIGNAL(clicked(bool)),this,SLOT(showHeads(bool)));
    connect(choiceBox,SIGNAL(highlighted(const QString&)),this,SLOT(displayItem(const QString&)));
}

FicheAnnuelle::~FicheAnnuelle(){}

void FicheAnnuelle::findDatas()
{
  QHash<int,QString> hashOfDatas;
  QString fichedocument;
  if(choiceBox->currentText()==QString("Tout")){
    if (m_hashTypeAndCheckBox.value(TERRAIN)->isChecked())
    {
          fichedocument = convertFromMedintuxStyle(getCheckedDatas(TERRAIN),TERRAIN);
          hashOfDatas.insert(TERRAIN,fichedocument);
        }
    if (m_hashTypeAndCheckBox.value(DOCUMENTS)->isChecked())
    {
          fichedocument = convertFromMedintuxStyle(getCheckedDatas(DOCUMENTS),DOCUMENTS);
          hashOfDatas.insert(DOCUMENTS,fichedocument);
        }
    if (m_hashTypeAndCheckBox.value(ORDONNANCE_AJUSTABLE)->isChecked())
    {
          fichedocument = convertFromMedintuxStyle(getCheckedDatas(ORDONNANCE_AJUSTABLE),ORDONNANCE_AJUSTABLE);
          hashOfDatas.insert(ORDONNANCE_AJUSTABLE,fichedocument);
        }
    if (m_hashTypeAndCheckBox.value(OBSERVATION)->isChecked())
    {
          fichedocument = convertFromMedintuxStyle(getCheckedDatas(OBSERVATION),OBSERVATION);
          hashOfDatas.insert(OBSERVATION,fichedocument);
        }
    }
  else{
      Tools tool(this);
      QString itemHead = choiceBox->currentText();
      QString ref;
      QStringList listitem;
      listitem = itemHead.split("|ref:");
      if (listitem.size()>1)
      {
          ref = listitem[1];
          }
      else return;
      fichedocument = tr(tool.getStringChosenFromBlob(ref));
      if (itemHead.contains("Terrain"))
      {
          hashOfDatas.insert(TERRAIN,fichedocument);
          }
      else{
          hashOfDatas.insert(DOCUMENTS,fichedocument);//FIXME
          }
      }
  ShowResultsFile showresults(this);
  showresults.setInformations(hashOfDatas);
  showresults.getNameAndGuid(m_name,m_firstname,m_guid);
  showresults.exec();
}

void FicheAnnuelle::setInformations(const QString & name, const QString & firstname, const QString & guid, const QString & userpref)
{
    m_name = name;
    m_firstname = firstname;
    m_guid = guid;
    m_user = userpref;
    nameEdit->setText(name+","+firstname);
    initComboUsers();
    qDebug() << __FILE__ << QString::number(__LINE__) << " name firstname guid =" << name << firstname << guid << userpref;
}

void FicheAnnuelle::initComboUsers()
{
    QSqlQuery qy(m_dbdrtux);
    QStringList userslist;
    userslist << m_user;
    QString personnes = QString("Personnes");
    if (!m_dbdrtux.tables().contains(personnes))
        {
              personnes = "personnes";
            }
    QString req = QString("select %1 from %2").arg("Login",personnes);
    if (!qy.exec(req))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
        QString user = qy.value(0).toString();
        if (!user.isEmpty())
        {
              userslist << user;
            }
        }  
    userslist.removeDuplicates();
    usersBox->addItems(userslist);   
}

QString FicheAnnuelle::getCheckedDatas(int type)
{
    QString docs;    
    QStringList listOfBlobs;
    listOfBlobs = getBlobs(m_tools->hashIntAndTypesOfHeads().value(type));
    for ( int i = 0; i < listOfBlobs.size(); ++ i)
    {
          docs += listOfBlobs[i]+"\n";
        }
    return docs;
}

QStringList FicheAnnuelle::getBlobs(const QString & numbertype)
{
    QStringList listofblobsdatas;
    QStringList listOfConcernedBlobs;
    Tools t;       
    QString begin = beginDateEdit->date().toString("yyyy-MM-dd");
    QString end = endDateEdit->date().toString("yyyy-MM-dd");
    QString tablehead = "RubriquesHead";
    if (!m_dbdrtux.tables().contains(tablehead))
        {
              tablehead = "rubriqueshead";
            }
    QString rubheadguidcolumns = "RbDate_IDDos";            
    QSqlQuery qHead(m_dbdrtux);
    QString reqHead = QString("select %1 from %2")
                             .arg("RbDate_RefBlobs_Primkey",tablehead);
    reqHead += QString(" where %1 = '%2' ").arg("RbDate_TypeRub",numbertype);
    if (!numbertype.contains(t.hashIntAndTypesOfHeads().value(TERRAIN)))
    {
          reqHead += QString(" and %1 between '%2' and '%3'").arg("RbDate_Date",begin,end);
        }    
    reqHead += QString(" and %1 = '%2'").arg(rubheadguidcolumns,m_guid);
    reqHead += QString(" and %1 = '%2'").arg("RbDate_CreateUser",usersBox->currentText());
    if (!qHead.exec(reqHead))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << qHead.lastError().text() ;
          }
    while (qHead.next())
    {
        listOfConcernedBlobs << qHead.value(0).toString();
        }       
        
    return getBlobFromIdblob(listOfConcernedBlobs);
}

QStringList FicheAnnuelle::getBlobFromIdblob(const QStringList & listOfConcernedBlobs)
{
    QStringList listofblobsdatas;
    QString tableblobs = "RubriquesBlobs";
    QString idprimkeyblob = "RbDate_PrimKey";
    QString blob = "RbDate_DataRub";
    QString refDos = "RbDate_IDDos";
    if (!m_dbdrtux.tables().contains(tableblobs))
    {
        tableblobs = "rubriquesblobs";
            }
    foreach(QString blobid,listOfConcernedBlobs){
        QSqlQuery qyBlob(m_dbdrtux);
        QString reqblob = QString("select %1 from %2 where %3 = '%4'").arg(blob,tableblobs,idprimkeyblob,blobid);
        //qDebug() << __FILE__ << QString::number(__LINE__) << " reqblob =" << reqblob ;
        if (!qyBlob.exec(reqblob))
        {
              qWarning() << __FILE__ << QString::number(__LINE__) << qyBlob.lastError().text() ;
            }
        while (qyBlob.next())
        {
            listofblobsdatas << qyBlob.value(0).toString();
            }
        } 
    //qDebug() << __FILE__ << QString::number(__LINE__) << " listofblobsdatas =" << listofblobsdatas.join(";") ;
    return listofblobsdatas;
}

QString FicheAnnuelle::convertFromMedintuxStyle(const QString & texttoconvert,int typeofhead)
{
    QString fixedtext;
    QByteArray textarray;
    const char * textchar;    
    switch(typeofhead){
        case TERRAIN :
            textarray = texttoconvert.toLatin1();
            textchar = textarray.data();
            fixedtext = tr(textchar);
            break;
        case DOCUMENTS :
            textarray = texttoconvert.toLatin1();
            textchar = textarray.data();
            fixedtext = tr(textchar);
            break;
        case ORDONNANCE_AJUSTABLE :
            textarray = texttoconvert.toLatin1();
            textchar = textarray.data();
            fixedtext = tr(textchar);
            break;
        case OBSERVATION :
            textarray = texttoconvert.toLatin1();
            textchar = textarray.data();
            fixedtext = tr(textchar);            
            break;
        default :
            break;    
        }
    
    return fixedtext;    
}

void FicheAnnuelle::pushDateOnBeginning()
{
    QDateTime beginDateOfFolder;
    beginDateOfFolder = m_tools->firstDateOfTheMedicalFolder(m_guid);
    beginDateEdit->setDate(beginDateOfFolder.date());
}

void FicheAnnuelle::showHeads(bool checked)
{
    Tools tool(this);
    choiceBox->clear();
    //User
    QString login = usersBox->currentText();
    QHash<int,QString> hashOfTitles;//RbDate_RefBlobs_PrimKey,RbDate_NomDate
    //quels checks sont true
    QList<int> listofcheckboxes;
    if (terrainBox->isChecked())
    {
        listofcheckboxes << TERRAIN_BOX;
        }
    if (documentsBox->isChecked())
    {
        listofcheckboxes << DOCUMENTS_BOX;
        }
    if (prescriptionsBox->isChecked())
    {
        listofcheckboxes << PRESCRIPTIONS_BOX;
        }
    if (observationsBox->isChecked())
    {
        listofcheckboxes << OBSERVATIONS_BOX;
        }
    //analyse
    for (int i = 0; i < listofcheckboxes.size(); ++i )
    {
    	int choice = listofcheckboxes[i];
    	QHash<int,QString> hash;
    	hash = tool.getHashOfTitlesAccordingToChoice(choice,m_guid,login);
    	QHashIterator<int,QString> it(hash);
    	while (it.hasNext())
    	{
    	    it.next();
    	    hashOfTitles.insert(it.key(),it.value());
    	    }
    	}
    QStringList listOfHeads;
    listOfHeads << QString("Tout");
    for (int i = 0; i < hashOfTitles.size(); ++i )
    {
    	listOfHeads << hashOfTitles.values()[i]+"|ref:"+QString::number(hashOfTitles.keys()[i]); //RbDate_NomDate|RbDate_RefBlobs_PrimKey
    	}
    choiceBox->addItems(listOfHeads);
}

void FicheAnnuelle::displayItem(const QString & item)
{
    if (item == "Tout")
    {
        return;
        }    
    Tools tool(this);
    QStringList listitem;
    listitem = item.split("|ref:");
    QString ref;
    if (listitem.size()>1)
    {
        ref = listitem[1];
        }
    const char * display = tool.getStringChosenFromBlob(ref);
    if (item.contains("Terrain"))
    {
        textEdit->setPlainText(tr(display));
        }
    else{
        textEdit->setHtml(tr(display));
        }
    
}


